package com.epfresh.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.adapter.PopupAddressAdapter;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.basedialog.CustomDialog;
import com.epfresh.bean.Address;
import com.epfresh.bean.City;
import com.epfresh.bean.CityAddressList;
import com.epfresh.bean.EditAddressEntity;
import com.epfresh.bean.PopupAddressEntity;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.DataManager;
import com.epfresh.location.PoiAddressActivity;
import com.epfresh.views.CommonInputItem;
import com.epfresh.views.dialog.AreaDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by wzh on 16-7-18.
 */
public class AddAddressActivity extends BaseActivity {

    CommonInputItem ciName;
    CommonInputItem ciPhone;
    CommonInputItem ciArea;
    CommonInputItem ciDetailAddress;
    CommonInputItem ciCode;
    CommonInputItem ciNickName;
    Address address;
    private boolean isLimitArea;
    private String addressStr;
    private boolean isSavingAddress;
    private TextView txt_save;
    private boolean isEditAddress = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_add_address);


        if (savedInstanceState != null) {
            getIntent().putExtra("address", savedInstanceState.getString("address"));
            getIntent().putExtra("isLimitArea", savedInstanceState.getBoolean("isLimitArea", false));
        }
        isLimitArea = getIntent().getBooleanExtra("isLimitArea", false);
        toolbarTitle.setText("添加地址");

        ivBack.setVisibility(View.VISIBLE);

        rightbtn.setVisibility(View.GONE);


        ciName = (CommonInputItem) findViewById(R.id.ci_name);
        ciPhone = (CommonInputItem) findViewById(R.id.ci_phone);
        ciArea = (CommonInputItem) findViewById(R.id.ci_area);
        ciDetailAddress = (CommonInputItem) findViewById(R.id.ci_detail_address);
        ciCode = (CommonInputItem) findViewById(R.id.ci_code);
        ciNickName = (CommonInputItem) findViewById(R.id.ci_nick_name);

        txt_save = findViewById(R.id.txt_save);
        txt_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveAddress();
            }
        });

        ciArea.setOnClickListener(this);
        init();
        initPopup();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("address", addressStr);
        outState.putBoolean("isLimitArea", isLimitArea);
        super.onSaveInstanceState(outState);
    }

    private void init() {


        addressStr = getIntent().getStringExtra("address");
        if (addressStr != null && !"".equals(addressStr)) {
            this.address = new Gson().fromJson(addressStr, Address.class);

            if (this.address != null) {
                toolbarTitle.setText("编辑地址");
                rightbtn.setText("删除");
                rightbtn.setVisibility(View.VISIBLE);
                isEditAddress = true;

                ciName.setContentText(this.address.getName());
                ((EditText) ciName.getContent()).setSelection(ciName.getContentText().length());
                ciPhone.setContentText(this.address.getPhone());
                ciDetailAddress.setContentText(this.address.getAddress());
                ciArea.setContentText(this.address.getProvinceName() + " " + this.address.getCityName() + " " + this.address.getDistrictName() + " " + this.address.getStreet());
                ciCode.setContentText(this.address.getPostcode());
            }
        }

        if (this.address == null) {
            this.address = new Address();
        }

//        if (isLimitArea) {
//            requestArea();
//        }

    }


    public void requestLocalCity() {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected void onPreExecute() {
            }

            @Override
            protected Void doInBackground(Void... voids) {
                cityData = DataManager.getInstance().getCityData(AddAddressActivity.this);

                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                intoPoiAddress();
            }
        }.execute();
    }

    City cityData;

    public void openArea() {
        AreaDialog areaDialog = new AreaDialog(this);
        if (cityData == null)
            cityData = areaDialog.getCityData();
        areaDialog.setPositiveDismiss(true);


        areaDialog.setCurrentIndex(cityData, address.getProvinceId(), address.getCityId(), address.getDistrictId());
        areaDialog.setOnPositiveClickListener(new AreaDialog.OnPositiveClickListener() {

            @Override
            public void onPositiveClickListener(int index1, CityAddressList city1, int index2, CityAddressList city2, int index3, CityAddressList city3) {
                if (city1 != null && city2 != null && city3 != null) {
                    address.setProvinceId(city1.getCode());
                    address.setCityId(city2.getCode());
                    address.setDistrictId(city3.getCode());

                    address.setProvinceName(city1.getName());
                    address.setCityName(city2.getName());
                    address.setDistrictName(city3.getName());
                    ciArea.setContentText(address.getAddressStr());

                }
            }
        });
        areaDialog.show();
    }


    @Override
    public void onRightClick() {
        if (address != null) {
            delete(address);
        }
    }

    public void delete(final Address address) {
        CustomDialog.Builder builder = new CustomDialog.Builder(mContext);

        builder.setTitleVisible(false).setMessage("确定删除地址吗？")//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件

                        delete(address.getId());
                        dialog.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();

            }

        });//在按键响应事件中显示此对话框
        builder.create().show();
    }

    public void delete(String id) {

        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(AppPurchaseRouterConstant.cmd_account_address_setDeleted);
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        re.putParameter("id", id);
        re.putParameter("isDeleted", true);

        request(re, AppPurchaseRouterConstant.cmd_account_address_setDeleted, onRequestDeleteListener);

    }

    OnRequestListener<Map<String, Boolean>> onRequestDeleteListener = new OnRequestListener<Map<String, Boolean>>() {
        @Override
        public Map<String, Boolean> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, Boolean>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<Map<String, Boolean>> responseEntity, Object o) {


            Map<String, Boolean> responseElement = responseEntity.getResponseElement();
            if (responseElement != null && responseElement.size() > 0) {//删除成功

                Boolean success = responseElement.get("success");

                if (success != null && success) {
                    Intent intent = new Intent();
                    intent.putExtra("isDelete", "isDelete");
                    setResult(RESULT_OK, intent);
                    finish();

//                    if (list.size() == 0) {
//                        lv.setVisibility(View.GONE);
//                        vEmpty.setVisibility(View.VISIBLE);
//                        ll_bottom.setVisibility(View.GONE);
////                        rightbtn.setVisibility(View.GONE);
//                    } else {
//                        addressId = list.get(0).getId();
//                        adapter.setAddressId(addressId);
//                        vEmpty.setVisibility(View.GONE);
//                        ll_bottom.setVisibility(View.VISIBLE);
//                        lv.setVisibility(View.VISIBLE);
////                        rightbtn.setVisibility(View.VISIBLE);
//                    }
//                    adapter.notifyDataSetChanged();
                }

            }

        }
    };

    private void saveAddress() {
        if (isWindowLocked()) {
            return;
        }
        String name = ciName.getContentText();
        if (name == null || "".equals(name)) {
            toast("请输入收货人姓名");
            return;
        }
        if (!VerificationUtils.isValid(name)) {
            toast(getString(R.string.illegal_input, "收货人"));
            return;
        }
        String phone = ciPhone.getContentText();
        if (phone == null || phone.length() != 11) {
            toast("请输入合法的手机号");
            return;
        }
        String area = ciArea.getContentText();
        if (area == null || area.length() < 1) {
            toast("请选择收货地址");
            return;
        }

        String detailAddress = ciDetailAddress.getContentText();
        if (detailAddress == null || "".equals(detailAddress)) {
            toast("请输入详细地址");
            return;
        }
        if (!VerificationUtils.isValid(detailAddress)) {
            toast(getString(R.string.illegal_input, "详细地址"));
            return;
        }
        address.setName(name);

        address.setPhone(phone);
        address.setAddress(detailAddress);
        address.setPostcode(ciCode.getContentText());


        requestSave(name, phone, detailAddress);
    }


    @Override
    public void onClick(View view) {
        super.onClick(view);

        switch (view.getId()) {
            case R.id.ci_area:
//                if (isLimitArea) {
//                    if (cityData == null || cityData.getAddressList() == null || cityData.getAddressList().size() == 0) {
//                        requestArea();
//                    } else {
//                        openArea();
//                    }
//                } else {
//                    openArea();
//                }

//                if (cityData == null) {
//                    if (isLimitArea) {
//                        requestArea();
//                    } else {
//                        requestLocalCity();
//                    }
//                } else {
//                    intoPoiAddress();
//                }
//                reqAddressData("");
                showPopup();
                break;
            case R.id.ci_detail_address:

//                Intent intent = new Intent(this, PoiAddressActivity.class);
//
//                if (isLimitArea) {
//                    intent.putExtra("isLimit", true);
//                }
//                startActivityForResult(intent, 0x1992);
                break;

        }
    }

    private void intoPoiAddress() {
        Intent intent = new Intent(this, PoiAddressActivity.class);

//        isLimitArea = true;
        if (address != null && address.getLat() != null && !"".equals(address.getLat())) {
            intent.putExtra("cityName", address.getCityName());
            intent.putExtra("lat", address.getLat());
            intent.putExtra("lng", address.getLng());
        }
        if (isLimitArea) {
            intent.putExtra("isLimit", true);
        }
        if (cityData != null)
            intent.putExtra("cityData", new Gson().toJson(cityData));
        startActivityForResult(intent, 0x1992);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == 0x1992) {
            if (data != null) {
                String address_four = data.getStringExtra("address_four");
                String detailAddress = data.getStringExtra("detail_address");
                String addressStr = data.getStringExtra("address");
                String poiAddress = data.getStringExtra("poi_address");

                String latitude = data.getStringExtra("latitude");
                String longitude = data.getStringExtra("longitude");

                String provinceName = data.getStringExtra("provinceName");
                String cityName = data.getStringExtra("cityName");
                String districtName = data.getStringExtra("DistrictName");
                String provinceId = data.getStringExtra("provinceId");
                String cityId = data.getStringExtra("cityId");
                String districtId = data.getStringExtra("DistrictId");
                String streetId = data.getStringExtra("streetId");

                address.setAddressFour(address_four);

                address.setProvinceName(provinceName);
                address.setCityName(cityName);
                address.setDistrictName(districtName);

                address.setProvinceId(provinceId);
                address.setCityId(cityId);
                address.setDistrictId(districtId);
                address.setStreetId(streetId);

                address.setLat(latitude);
                address.setLng(longitude);

                address.setAddressOnMap(detailAddress);
                ciArea.setContentText(detailAddress);
                ciDetailAddress.setContentText(addressStr);
            }
        }
    }

    OnRequestListener<Map<String, String>> onRequestAddressListener = new OnRequestListener<Map<String, String>>() {
        @Override
        public Map<String, String> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, String>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<Map<String, String>> responseEntity, Object o) {


            Map<String, String> responseElement = responseEntity.getResponseElement();
            if (responseElement != null && responseElement.size() > 0) {//删除成功

                String id = responseElement.get("result");
                String streetId = responseElement.get("streetId");
                if (id != null && !"".equals(id)) {
                    Intent intent = new Intent();
                    if (address != null) {
                        address.setId(id);
                        address.setStreetId(streetId);
                        address.setProvinceId(selectProvinceCode);
                        address.setProvinceName(selectProvince);
                        address.setCityId(selectCityCode);
                        address.setCityName(selectCity);
                        address.setDistrictId(selectAreaCode);
                        address.setDistrictName(selectArea);
                        address.setStreetId(selectStreetCode);
                        address.setStreet(selectStreet);
                    }
                    intent.putExtra("address", new Gson().toJson(address));
                    setResult(RESULT_OK, intent);
                    finish();
                }

            }
        }
    };

    public void requestSave(String name, String phone, String detailAddress) {
        if (isSavingAddress) {
            return;
        }

        RequestEntityMap re = new RequestEntityMap();

        re.setCmd(AppPurchaseRouterConstant.cmd_account_address_save);
        if (isEditAddress) {
            re.putParameter("id", address.getId());
        }
        re.putParameter("name", name);//姓名
        re.putParameter("phone", phone);//电话
        re.putParameter("provinceId", selectProvinceCode);//省Id
        re.putParameter("cityId", selectCityCode);//市Id
        re.putParameter("districtId", selectAreaCode);//区Id
        re.putParameter("addressFourId", selectStreetCode);//街道Id
        re.putParameter("addressFour", selectStreet);//街道名
        re.putParameter("lng", selectStreetLng);//街道经度
        re.putParameter("lat", selectStreetLat);//街道纬度
        re.putParameter("address", detailAddress);//详细地址

//        re.putParameter("addressFour", address.getAddressFour());
//
//        re.putParameter("id", address.getId());
//        re.putParameter("name", address.getName());
//        re.putParameter("provinceId", address.getProvinceId());
//        re.putParameter("cityId", address.getCityId());
//        re.putParameter("districtId", address.getDistrictId());
//        re.putParameter("address", address.getAddress());
//        re.putParameter("phone", address.getPhone());
//        re.putParameter("addressOnMap", address.getAddressOnMap());
//        re.putParameter("lng", address.getLng());
//        re.putParameter("lat", address.getLat());
//
////        re.putParameter("isDefault", true);
//        re.putParameter("isDeleted", false);
//        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());

        request(re, AppPurchaseRouterConstant.cmd_account_address_save, onRequestAddressListener);

    }


    private OnRequestListener<City> onRequestAreaListener = new OnRequestListener<City>() {
        @Override
        public City jsonToObj(String s) {
            return new Gson().fromJson(s, City.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            isSavingAddress = false;
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            isSavingAddress = false;
            hideProgressDialog();
        }

        @Override
        public void onStart(Object o) {

            isSavingAddress = true;
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<City> responseEntity, Object o) {
            isSavingAddress = false;
            hideProgressDialog();
            City responseElement = responseEntity.getResponseElement();
            if (responseElement != null && responseElement.getAddressList() != null && responseElement.getAddressList().size() > 0) {
                cityData = responseElement;
//                openArea();

                intoPoiAddress();
            }

        }
    };

    public void requestArea() {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(AppPurchaseRouterConstant.cmd_account_app_deliveryAddress);//todo:chenbing

        request(re, AppPurchaseRouterConstant.cmd_account_app_deliveryAddress, onRequestAreaListener);
    }

    //****************************************************************************************************************************************************
    private PopupWindow popupAddress;
    private PopupAddressAdapter addressAdapter;
    //顶部关闭按钮
    private ImageView img_close;
    //顶部的tab
    private TabLayout tab_layout;
    //地址列表
    private ListView lv_address;

    //被选中的省份name
    private String selectProvince = "";
    //被选中的城市name
    private String selectCity = "";
    //被选中的县或区域name
    private String selectArea = "";
    //被选中的街道name
    private String selectStreet = "";

    //被选中的省份code
    private String selectProvinceCode = "";
    //被选中的城市code
    private String selectCityCode = "";
    //被选中的县或区域code
    private String selectAreaCode = "";
    //被选中的街道code
    private String selectStreetCode = "";
    //被选中的街道的经纬度
    private String selectStreetLng;
    private String selectStreetLat;

    //省份level
    private String provinceLevel = "";
    //城市level
    private String cityLevel = "1";
    //县或区域level
    private String areaLevel = "2";
    //街道level
    private String streetLevel = "3";

    //被选中的省份在列表中的位置，默认没有选中的为-1
    private int provinceIndex = -1;
    //被选中的城市在列表中的位置，默认没有选中的为-1
    private int cityIndex = -1;
    //被选中的县或区在列表中的位置，默认没有选中的为-1
    private int areaIndex = -1;
    //被选中的街道在列表中的位置，默认没有选中的为-1
    private int streetIndex = -1;

    //省份的数据集合
    private List<PopupAddressEntity> provinces = new ArrayList<>();
    //城市的数据集合
    private List<PopupAddressEntity> cities = new ArrayList<>();
    //县和区域的数据集合
    private List<PopupAddressEntity> areas = new ArrayList<>();
    //街道的数据集合
    private List<PopupAddressEntity> streets = new ArrayList<>();

    //当前被选中的tab的index
    private int tabIndex;


    /**
     * 初始化popupWindow
     */
    private void initPopup() {
        View contentView = View.inflate(this, R.layout.layout_address_choose, null);
        img_close = contentView.findViewById(R.id.img_close);
        tab_layout = contentView.findViewById(R.id.tab_layout);
        lv_address = contentView.findViewById(R.id.lv_address);

        popupAddress = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupAddress.setBackgroundDrawable(new ColorDrawable());
        popupAddress.setOutsideTouchable(true);
        popupAddress.setAnimationStyle(R.style.ActionPopupAnimation);
        popupAddress.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

        img_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupAddress.dismiss();
            }
        });

        tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                updateAddressLocalList(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


        lv_address.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                updateItemClick(position);
            }
        });

        addressAdapter = new PopupAddressAdapter();
        lv_address.setAdapter(addressAdapter);

        if (isEditAddress){
            reqEditAddressData();
        }else {
            reqAddressData("", 1, provinceLevel);
        }
    }

    private void showPopup() {
        View rootView = View.inflate(this, R.layout.activity_add_address, null);
        popupAddress.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
    }


    /**
     * 根据item点击切换列表展示的地址数据
     *
     * @param position
     */
    private void updateItemClick(int position) {
        switch (tabIndex) {
            case 0:
                selectProvince = provinces.get(position).getName();
                selectProvinceCode = provinces.get(position).getCode();

                provinceIndex = position;
                addressAdapter.setSelectedPos(provinceIndex);
                reqAddressData(selectProvinceCode, 2, cityLevel);
                break;
            case 1:
                selectCity = cities.get(position).getName();
                selectCityCode = cities.get(position).getCode();

                cityIndex = position;
                addressAdapter.setSelectedPos(cityIndex);
                reqAddressData(selectCityCode, 3, areaLevel);
                break;
            case 2:
                selectArea = areas.get(position).getName();
                selectAreaCode = areas.get(position).getCode();

                areaIndex = position;
                addressAdapter.setSelectedPos(areaIndex);
                reqAddressData(selectAreaCode, 4, streetLevel);
                break;
            case 3:
                selectStreet = streets.get(position).getName();
                selectStreetCode = streets.get(position).getCode();
                selectStreetLng = streets.get(position).getLng();
                selectStreetLat = streets.get(position).getLat();

                streetIndex = position;
                addressAdapter.setSelectedPos(streetIndex);

                tab_layout.removeTabAt(3);
                //街道tab
                TabLayout.Tab tabStreet = tab_layout.newTab().setText(selectStreet);
                tab_layout.addTab(tabStreet);
                tabStreet.select();
                setTabTextSingle(tab_layout);

                ciArea.setContentText(selectProvince + " " + selectCity + " " + selectArea + " " + selectStreet);
                popupAddress.dismiss();
                break;
        }
    }


    /**
     * 更新列表缓存数据
     *
     * @param pos 当前选中tab的index
     */
    private void updateAddressLocalList(int pos) {
        switch (pos) {
            case 0:
                tabIndex = 0;
                addressAdapter.setData(provinces);
                addressAdapter.setSelectedPos(provinceIndex);
                lv_address.setSelection(provinceIndex == -1 ? 0 : provinceIndex);
                break;
            case 1:
                tabIndex = 1;
                addressAdapter.setData(cities);
                addressAdapter.setSelectedPos(cityIndex);
                lv_address.setSelection(cityIndex == -1 ? 0 : cityIndex);
                break;
            case 2:
                tabIndex = 2;
                addressAdapter.setData(areas);
                addressAdapter.setSelectedPos(areaIndex);
                lv_address.setSelection(areaIndex == -1 ? 0 : areaIndex);
                break;
            case 3:
                tabIndex = 3;
                addressAdapter.setData(streets);
                addressAdapter.setSelectedPos(streetIndex);
                lv_address.setSelection(streetIndex == -1 ? 0 : streetIndex);
                break;
        }
    }

    /**
     * 更新列表数据及tab状态
     *
     * @param list
     * @param addressList
     */
    private void updateAddressList(int list, List<PopupAddressEntity> addressList) {
        //省的tab
        TabLayout.Tab tabProvince;
        //城市的tab
        TabLayout.Tab tabCity;
        //区的tab
        TabLayout.Tab tabArea;
        //街道的tab
        TabLayout.Tab tabStreet;
        if (list == 1) {//更新一级（即省）列表
            //省
            tabProvince = tab_layout.newTab().setText("请选择");
            tab_layout.addTab(tabProvince);

            tabProvince.select();
            tabIndex = 0;

            provinces.addAll(addressList);
            addressAdapter.setData(provinces);
        } else if (list == 2) {//更新二级（即市）列表
            tab_layout.removeAllTabs();
            //省
            tabProvince = tab_layout.newTab().setText(selectProvince);
            tab_layout.addTab(tabProvince);
            //市
            tabCity = tab_layout.newTab().setText("请选择");
            tab_layout.addTab(tabCity);

            tabCity.select();
            tabIndex = 1;

            cityIndex = -1;
            addressAdapter.setSelectedPos(cityIndex);
            cities.clear();
            cities.addAll(addressList);
            addressAdapter.setData(cities);
            lv_address.setSelection(0);
        } else if (list == 3) {//更新三级（即区）列表
            tab_layout.removeAllTabs();
            //省
            tabProvince = tab_layout.newTab().setText(selectProvince);
            tab_layout.addTab(tabProvince);
            //市
            tabCity = tab_layout.newTab().setText(selectCity);
            tab_layout.addTab(tabCity);
            //区/县
            tabArea = tab_layout.newTab().setText("请选择");
            tab_layout.addTab(tabArea);

            tabArea.select();
            tabIndex = 2;

            areaIndex = -1;
            addressAdapter.setSelectedPos(areaIndex);
            areas.clear();
            areas.addAll(addressList);
            addressAdapter.setData(areas);
            lv_address.setSelection(0);
        } else if (list == 4) {//更新四级（即街道）列表
            tab_layout.removeAllTabs();
            //省
            tabProvince = tab_layout.newTab().setText(selectProvince);
            tab_layout.addTab(tabProvince);
            //市
            tabCity = tab_layout.newTab().setText(selectCity);
            tab_layout.addTab(tabCity);
            //区/县
            tabArea = tab_layout.newTab().setText(selectArea);
            tab_layout.addTab(tabArea);
            //街道
            tabStreet = tab_layout.newTab().setText("请选择");
            tab_layout.addTab(tabStreet);

            tabStreet.select();
            tabIndex = 3;

            streetIndex = -1;
            addressAdapter.setSelectedPos(streetIndex);
            streets.clear();
            streets.addAll(addressList);
            addressAdapter.setData(streets);
            lv_address.setSelection(0);
        }
        setTabTextSingle(tab_layout);
    }

    /**
     * 请求获取地址数据
     *
     * @param code
     * @param list
     * @param level
     */
    private void reqAddressData(String code, final int list, String level) {
        RequestEntityMap requestEntityMap = new RequestEntityMap();
        requestEntityMap.setCmd(AppPurchaseRouterConstant.cmd_address_data);
        requestEntityMap.putParameter("code", code);
        requestEntityMap.putParameter("level", level);

        request(requestEntityMap, AppPurchaseRouterConstant.cmd_address_data, new OnRequestListener<List<PopupAddressEntity>>() {
            @Override
            public List<PopupAddressEntity> jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, new TypeToken<List<PopupAddressEntity>>() {
                }.getType());
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
            }

            @Override
            public void onStart(Object tag) {

            }

            @Override
            public void onResponse(ResponseEntity<List<PopupAddressEntity>> response, Object tag) {
                if (response.getResponseElement() != null) {
                    updateAddressList(list, response.getResponseElement());
                }
            }
        });
    }

    //************************************************************************************************************************************************

    /**
     * 请求获取编辑地址数据
     */
    private void reqEditAddressData() {
        RequestEntityMap requestEntityMap = new RequestEntityMap();
        requestEntityMap.setCmd(AppPurchaseRouterConstant.cmd_edit_address_data);
        requestEntityMap.putParameter("id", address.getId());

        request(requestEntityMap, AppPurchaseRouterConstant.cmd_edit_address_data, new OnRequestListener<EditAddressEntity>() {
            @Override
            public EditAddressEntity jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, EditAddressEntity.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                T.toast(failCode + "");
            }

            @Override
            public void onStart(Object tag) {

            }

            @Override
            public void onResponse(ResponseEntity<EditAddressEntity> response, Object tag) {
                if (response.getResponseElement() != null) {
                    EditAddressEntity editAddressEntity = response.getResponseElement();
                    provinces.addAll(editAddressEntity.getProvince());
                    cities.addAll(editAddressEntity.getCity());
                    areas.addAll(editAddressEntity.getDistrict());
                    streets.addAll(editAddressEntity.getStreet());

                    initEditAddress();
                }
            }
        });
    }


    private void initEditAddress() {

        selectProvince = address.getProvinceName();
        selectCity = address.getCityName();
        selectArea = address.getDistrictName();
        selectStreet = address.getStreet();

        for (int i = 0; i < provinces.size(); i++) {
            if (selectProvince.equals(provinces.get(i).getName())) {
                provinceIndex = i;
                break;
            }
        }
        for (int i = 0; i < cities.size(); i++) {
            if (selectCity.equals(cities.get(i).getName())) {
                cityIndex = i;
                break;
            }
        }
        for (int i = 0; i < areas.size(); i++) {
            if (selectArea.equals(areas.get(i).getName())) {
                areaIndex = i;
                break;
            }
        }

        for (int i = 0; i < streets.size(); i++) {
            if (selectStreet.equals(streets.get(i).getName())) {
                streetIndex = i;
            }
        }

        //省的tab
        TabLayout.Tab tabProvince = tab_layout.newTab().setText(selectProvince);
        //城市的tab
        TabLayout.Tab tabCity = tab_layout.newTab().setText(selectCity);
        //区的tab
        TabLayout.Tab tabArea = tab_layout.newTab().setText(selectArea);
        //街道的tab
        TabLayout.Tab tabStreet = tab_layout.newTab().setText(selectStreet);



        tab_layout.addTab(tabProvince);
        tab_layout.addTab(tabCity);
        tab_layout.addTab(tabArea);
        tab_layout.addTab(tabStreet);
        tabStreet.select();
        setTabTextSingle(tab_layout);

        addressAdapter.setSelectedPos(streetIndex);
        addressAdapter.setData(streets);
        lv_address.setSelection(streetIndex);
    }

    /**
     * 设置tab字体单行显示
     * @param tabLayout
     */
    private void setTabTextSingle(final TabLayout tabLayout) {
        tabLayout.post(new Runnable() {

            @Override
            public void run() {
                try {
                    LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);
                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);
                        TextView mTextView = (TextView) mTextViewField.get(tabView);
                        mTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
                        mTextView.setSingleLine();
                        tabView.invalidate();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
